package net.message;

import game.Client;
import util.LogUtil;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 协议处理线程
 */
public class MsgDispatcher extends Thread {

    private volatile boolean start = false;

    private Map<Integer, Client> clients = new ConcurrentHashMap<>();

    public MsgDispatcher() {
    }

    public void startUp() {
        this.start = true;
        this.start();
    }

    public void close() {
        this.start = false;
        clients.forEach((k, v) -> {
            v.close();
        });
        this.interrupt();
    }

    @Override
    public void run() {
        while (this.start) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                if (!e.getMessage().contains("sleep interrupted")) {
                    LogUtil.game.error("Exception", e);
                }
                break;
            }
            long now = System.currentTimeMillis();
            clients.forEach((k, v) -> {
                v.process(now);
            });
        }
    }

    public void addClient(Client client) {
        clients.put(client.getIndex(), client);
    }


}
